//package com.deer.wms.base.system.web.rocketmq;
//
//import com.alibaba.fastjson.JSONObject;
//import com.deer.wms.base.system.finalUtil.BillState;
//import com.deer.wms.base.system.finalUtil.BoxInfoState;
//import com.deer.wms.base.system.finalUtil.CellInfoState;
//import com.deer.wms.base.system.finalUtil.TopicName;
//import com.deer.wms.base.system.model.BillInRecord;
//import com.deer.wms.base.system.model.bill.BillInDetail;
//import com.deer.wms.base.system.model.bill.BillInDetailDto;
//import com.deer.wms.base.system.model.bill.BillInMaster;
//import com.deer.wms.base.system.model.bill.BillInMasterDto;
//import com.deer.wms.base.system.model.box.AreaBoxItem;
//import com.deer.wms.base.system.model.box.AreaBoxItemDto;
//import com.deer.wms.base.system.model.box.BoxInfo;
//import com.deer.wms.base.system.model.box.BoxItem;
//import com.deer.wms.base.system.model.item.ItemInfo;
//import com.deer.wms.base.system.model.task.TaskInfoCriteria;
//import com.deer.wms.base.system.model.task.TaskInfoDto;
//import com.deer.wms.base.system.model.task.TaskInfoHistoryDto;
//import com.deer.wms.base.system.model.ware.CellInfo;
//import com.deer.wms.base.system.service.BillInRecordService;
//import com.deer.wms.base.system.service.bill.IBillInDetailService;
//import com.deer.wms.base.system.service.bill.IBillInMasterService;
//import com.deer.wms.base.system.service.box.*;
//import com.deer.wms.base.system.service.item.IItemInfoService;
//import com.deer.wms.base.system.service.task.BillInTaskInfoService;
//import com.deer.wms.base.system.service.task.ITaskInfoService;
//import com.deer.wms.base.system.service.task.TaskInfoHistoryService;
//import com.deer.wms.base.system.service.ware.ICellInfoService;
//import com.deer.wms.base.system.util.DateUtil;
//import com.deer.wms.common.utils.SpringUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
//import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
//import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
//import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
//import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
//import org.apache.rocketmq.common.message.Message;
//import org.apache.rocketmq.common.message.MessageExt;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.CommandLineRunner;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.transaction.interceptor.TransactionAspectSupport;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//@Component
//@Slf4j
//public class PushConsumer implements CommandLineRunner {
//    @Autowired
//    private ITaskInfoService taskInfoService;
//
//    @Autowired
//    private BillInTaskInfoService billInTaskInfoService;
//
//    @Autowired
//    private TaskInfoHistoryService taskInfoHistoryService;
//    @Autowired
//    private IBoxItemService boxItemService;
//    @Autowired
//    private IBillInDetailService billInDetailService;
//    @Autowired
//    private BoxInfoService boxInfoService;
//    @Autowired
//    private ICellInfoService cellInfoService;
//    @Autowired
//    private BillInRecordService billInRecordService;
//    @Autowired
//    private BoxItemRecordService boxItemRecordService;
//    @Autowired
//    private AreaBoxItemService areaBoxItemService;
//    @Autowired
//    private AreaBoxItemHistoryService areaBoxItemHistoryService;
//    @Autowired
//    private IBillInMasterService billInMasterService;
//    @Autowired
//    private IItemInfoService iItemInfoService;
//    //消费者
//    @Value("${apache.rocketmq.consumer.pushConsumer}")
//    private String pushConsumer;
//    //NameServer 地址
//    @Value("${apache.rocketmq.namesrvAddr}")
//    private String namesrvAddr;
////初始化RocketMq的监听信息，渠道信息
//
//    @Value("${apache.rocketmq.consumer.clientIP}")
//    private String clientIP;
//    @Transactional(rollbackFor=Exception.class)
//    public void messageListener(){
//        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("inWarehouseTopic");
//        consumer.setNamesrvAddr(namesrvAddr);
//        consumer.setClientIP(clientIP);
//        try {
//            consumer.subscribe(TopicName.TOPIC_BILLIN, "push");
//            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); // 程序第一次启动从消息队列头获取数据
//            consumer.setConsumeMessageBatchMaxSize(1);//可以修改每次消费消息的数量，默认设置是每次消费一条
//            consumer.registerMessageListener(new MessageListenerConcurrently() {
//                @Transactional(rollbackFor=Exception.class)
//                public ConsumeConcurrentlyStatus consumeMessage(List <MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
//                    try {
//                        for(Message msg:list){
//                            Integer billInId= Integer.parseInt(convertMsgToJsonObj(msg).get("billInId").toString());
//                            log.info("获得入库billInId:" + billInId + ",开始更新\r\n" +msg.toString());
//                            //根据billInId查询任务表 得到 	任务id,任务中的box_code，quantity，batch,item_code
//                            List<TaskInfoDto> taskInfoList = billInTaskInfoService.selectTaskInfoByBillInMasterId(billInId);
//                            if(taskInfoList.size()>0){
//                                for (TaskInfoDto taskInfoDto : taskInfoList) {
//                                    Integer cellId = taskInfoDto.getCellId();//货位IDs
//                                    if(null!=cellId){
//                                        int saveBoxItemRe =1;
//                                        int saveBillInRecordRe=1;
//                                        int saveTaskHisRe =1;
//                                        int delTaskRe =1;
//                                        BoxItem boxItem = new BoxItem();
//                                        BoxInfo boxInfo = new BoxInfo();
//                                        BillInRecord billInRecord = new BillInRecord();
//                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                        Date time = null;
//                                        try {
//                                            time = DateUtil.timeAddByDays(sdf.parse(taskInfoDto.getPdTime()), taskInfoDto.getDateWarning());
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                        String expTime = sdf.format(time);
//                                        billInRecord.setExp(expTime);//计算预计的过期时间
//                                        boxItem.setExp(expTime);//计算预计的过期时间
//                                        //更新明细的入库数量
//                                        BillInDetail billInDetail = new BillInDetail();
//                                        billInDetail.setBillInDetailId(taskInfoDto.getBillInDetailId());//ID
//                                        billInDetail.setQuantityReceived(taskInfoDto.getQuantity());//数量
//                                        int editBIllInRe = billInDetailService.updateBillInInfo(billInDetail);
//                                        //更新暂存区的库存
//                                        BillInMasterDto billInMasterDto = billInMasterService.selectBillInMasterById(billInId);
//                                        //判断是否是回流入库；是；则删去暂存区的库存
//                                        if(billInMasterDto.getType()== 2){
//                                            updateAreaBoxItem(billInId);//调用更新暂存区库存方法
//                                        }
//                                        //更新库存
//                                        boxItem.setQuantity(taskInfoDto.getQuantity());
//                                        boxItem.setBoxCode(taskInfoDto.getBoxCode());
//                                        boxItem.setBatch(taskInfoDto.getBatch());
//                                        boxItem.setItemCode(taskInfoDto.getItemCode());
//                                        boxItem.setBillInDetailId(taskInfoDto.getBillInDetailId());
//                                        boxItem.setPd(taskInfoDto.getPdTime());
//                                        boxItem.setWareId(1220);
//                                        boxItem.setState(0);
//                                        boxItem.setStowCreateTime(taskInfoDto.getStowCreateTime());//码垛时间
//                                        BoxItem  verifyBoxItem= boxItemService.verifyBoxItem(boxItem);
//                                        if(null ==verifyBoxItem){
//                                            saveBoxItemRe = boxItemService.insertBoxItem(boxItem);
//                                        }
//
//                                        //更新托盘状态
//                                        boxInfo.setBoxCode(taskInfoDto.getBoxCode());
//                                        boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ONT);//0-不在货位 1-货位上  2-任务中
//                                        boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ONT);//   0-无货 1-有货
//                                        boxInfo.setBoxCellId(cellId);//货位
//                                        boxInfo.setBoxType(2);//类型：1-料箱  2-托盘
//                                        int editBoxInfoRe = boxInfoService.updateBoxInfo(boxInfo);
//                                        //货位以及状态 cellInfo
//                                        //货位以及状态 cellInfo
//                                        ItemInfo byItemCode = iItemInfoService.findByItemCode(taskInfoDto.getItemCode());
//                                        CellInfo cellInfo = new CellInfo();
//                                        cellInfo.setState(CellInfoState.STATE_ONT);//状态  ：0-无托盘；1-有货；2-出库中；3-入库中；4故障
//                                        cellInfo.setCellId(cellId);
//                                        cellInfo.setItemId(byItemCode.getItemId());
//                                        int editCellInfo = cellInfoService.updateCellInfo(cellInfo);
//                                        Integer id= taskInfoDto.getId();
//                                        //同步入库报表
//                                        billInRecord.setBillInDetailId(taskInfoDto.getBillInDetailId());//出库单id
//                                        billInRecord.setAcceptQuantity(taskInfoDto.getQuantity());//入库数量
//                                        billInRecord.setBoxCode(taskInfoDto.getBoxCode());
//                                        billInRecord.setBarCode(taskInfoDto.getBarCode());
//                                        billInRecord.setPd(taskInfoDto.getPdTime());
//                                        billInRecord.setBatch(taskInfoDto.getBatch());
//                                        billInRecord.setStowCreateTime(taskInfoDto.getStowCreateTime());//码垛时间
//                                        BillInRecord verifyBillInRecord = billInRecordService.verifyBillInRecord(billInRecord);
//                                        if(null==verifyBillInRecord){
//                                            saveBillInRecordRe = billInRecordService.insertBillInRecord(billInRecord);
//                                        }
//                                        //入库同步到库存记录表：
//                                        //boxItemRecordService.insertBoxItemRecord(boxItem);
//                                        BillInMaster billInMaster =new BillInMaster();
//                                        billInMaster.setState(BillState.BILLIN_STATE_FOUR);//已入库
//                                        billInMaster.setBillId(billInId);
//                                        int editBillMaRe = billInMasterService.updateBillInMaster(billInMaster);
//                                        TaskInfoCriteria criteria =new TaskInfoCriteria();
//                                        criteria.setBoxCode(taskInfoDto.getBoxCode());
//                                        criteria.setBillInDetailId(taskInfoDto.getBillInDetailId());
//                                        TaskInfoHistoryDto taskInfoHistoryDto = taskInfoHistoryService.verifTaskInfoHistory(criteria);
//                                        if(null==taskInfoHistoryDto){
//                                            saveTaskHisRe = taskInfoHistoryService.saveTaskInfoHistory(billInTaskInfoService.selectTaskInfoById(id));//任务完成同步到历史表
//                                            delTaskRe = billInTaskInfoService.deleteTaskInfoById(id);//删除已完成的任务表
//                                        }
//
//                                        if(editBIllInRe==0||saveBoxItemRe==0||editBoxInfoRe==0||editCellInfo==0||saveBillInRecordRe==0||editBillMaRe==0||saveTaskHisRe==0||delTaskRe==0){
//                                            log.error("error----入库更新库存等出错了，回滚,billInId:" + billInId +"消息:"+msg.toString());
//                                            throw new RuntimeException("入库更新方法执行出错，手动抛异常");
//                                        }else {
//                                            log.debug("入库同步结束入库billInId:" + billInId + "消息:" + msg.toString());
//                                        }
//
//                                    }else {
//                                        log.error("该任务没有分配cellID,billInId:" + billInId );
//                                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
//                                    }
//                                }
//                            }else {
//                                log.error("入库任务表没有该billInId:" + billInId );
//                                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
//                            }
//                        }
//                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
//                    }
//                }
//            });
//            consumer.start();
//        } catch (Exception e) {
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
//    }
//
//
//    public JSONObject convertMsgToJsonObj(Message msg) {
//        String taskInfoStr = JSONObject.toJSONString(JSONObject.parse(msg.getBody()));
//        JSONObject obj = (JSONObject) JSONObject.parse(taskInfoStr);
//        return obj;
//    }
//
//    /***
//     *更新暂存区库存
//     * @author 李帅辰
//     * @date 2020/10/23 9:02
//     * @return java.lang.Boolean
//     */
//    public void  updateAreaBoxItem(Integer billInId){
//        List<BillInDetailDto> billInDetailListByBillId = billInDetailService.findBillInDetailListByBillId(billInId);//入库作业显示入库单对应的明细和物料
//        for (BillInDetailDto billInDetailDto : billInDetailListByBillId) {
//            AreaBoxItemDto re = new AreaBoxItemDto();
//            re.setItemCode(billInDetailDto.getItemCode());
//            re.setBatch(billInDetailDto.getBatch());
//            re.setPd(billInDetailDto.getPdTime());
//            List<AreaBoxItemDto> areaBoxItemList  = areaBoxItemService.findAreaBoxItemList(re);
//            for (AreaBoxItemDto boxItemDto : areaBoxItemList) {
//                Integer quantityReceived = billInDetailDto.getQuantityReceived();//入库数量
//                if(quantityReceived==boxItemDto.getQuantity()){
//                    //同步暂存区
//                    areaBoxItemHistoryService.saveAreaBoxItem(boxItemDto);
//                    areaBoxItemService.delectAreaBoxItembyId(boxItemDto.getId());
//                    break;
//                }else if(quantityReceived<boxItemDto.getQuantity()){
//                    AreaBoxItem areaBoxItem = new AreaBoxItem();
//                    areaBoxItem.setId(boxItemDto.getId());
//                    areaBoxItem.setQuantity(boxItemDto.getQuantity()-quantityReceived);
//                    areaBoxItemService.editAreaBoxItem(areaBoxItem);//修改暂存区物料的数量
//                    boxItemDto.setQuantity(quantityReceived);
//                    areaBoxItemHistoryService.saveAreaBoxItem(boxItemDto);//将出库的暂存区物料数量添加到暂存区历史
//                    break;
//                }else {
//                    areaBoxItemHistoryService.saveAreaBoxItem(boxItemDto);
//                    areaBoxItemService.delectAreaBoxItembyId(boxItemDto.getId());
//                }
//
//            }
//        }
//    }
//    @Override
//    public void run(String... args) throws Exception {
//        new Thread(() -> {
//            PushConsumer pushConsumer =SpringUtils.getBean(PushConsumer.class);
//            pushConsumer.messageListener();
//        }).start();
//    }
//}
